package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"github.com/ijython/ip2region/binding/golang"
	"os"
)
var path string
func main(){
	args:=os.Args
	path="./"
	if len(args)==2{
		path=args[1]
	}
	//gin.SetMode(gin.DebugMode) //全局设置环境，此为开发环境，线上环境为gin.ReleaseMode
	gin.SetMode(gin.ReleaseMode) //全局设置环境，此为开发环境，线上环境为gin.ReleaseMode
	router := gin.Default()    //获得路由实例
	//添加中间件
	router.Use(Middleware)
	//注册接口
	router.GET("/", getIndex)
	router.GET("/getIpInfo", getIpInfo)
	//监听端口
	http.ListenAndServe(":8000", router)
}

func Middleware(c *gin.Context) {
	//fmt.Println("this is a middleware!")
}

type IpInfo struct {
	Country string `json:"country"`
	Region string `json:"region"`
	Province string	`json:"province"`
	City string	`json:"city"`
	ISP string `json:"isp"`
}
func getIndex(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{"message": "please get/getIpInfo?ip=114.114.114.114", "status": http.StatusOK})
}
func getIpInfo(c *gin.Context) {
	value, exist := c.GetQuery("ip")
	if !exist {
		value = "the key is not exist!"
	}
	region,err:=ip2region.New(path+"ip2region.db")
	if err!=nil{
		fmt.Println(err)
	}
	ip,err:=region.MemorySearch(value)
	ipInfo:=IpInfo{ip.Country,ip.Region,ip.Province,ip.City,ip.ISP}
	c.JSON(http.StatusOK, ipInfo)
	return
}
